import React, { useEffect, useRef, useState, useCallback } from 'react';
import * as echarts from 'echarts';
import type { ProvinceData } from '../App';

// 定义地图数据接口
interface MapData {
  title: string;
  subtitle: string;
  visualMap: {
    min: number;
    max: number;
    text: string[];
    inRange: {
      color: string[];
    };
  };
  provinces: Record<string, ProvinceData>;
  cities: {
    name: string;
    coordinates: number[];
    value: number;
  }[];
  settings: {
    areaColor: string;
    borderColor: string;
    highlightColor: string;
    pointColor: string;
    zoom: number;
    roam: boolean;
  };
  nationalMetrics: {
    cpuUsage: number;
    memoryUsage: number;
    networkTraffic: number;
    storage: number;
    processingPower: string;
    computeNodes: number;
  };
}

interface MapChartProps {
  onProvinceSelect: (provinceName: string, provinceData: ProvinceData | null) => void;
}

export const MapChart: React.FC<MapChartProps> = React.memo(({ onProvinceSelect }) => {
  const chartRef = useRef<HTMLDivElement>(null);
  const chartInstance = useRef<echarts.ECharts | null>(null);
  const mapDataRef = useRef<MapData | null>(null);
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);
  const [mapInitialized, setMapInitialized] = useState<boolean>(false);

  // 从JSON文件加载地图配置数据
  useEffect(() => {
    const fetchMapData = async () => {
      try {
        const response = await fetch('/data/charts/map-data.json');
        if (!response.ok) {
          throw new Error(`HTTP error! Status: ${response.status}`);
        }
        const data = await response.json();
        mapDataRef.current = data;
        setLoading(false);
      } catch (err) {
        console.error('加载地图数据失败:', err);
        setError('加载地图数据失败，请检查网络连接');
        setLoading(false);
      }
    };

    fetchMapData();
  }, []);

  // 格式化工具提示显示
  const formatTooltip = useCallback((params: any) => {
    // 检查是否是地图系列
    if (params.seriesType === 'map') {
      const provinceData = params.data.data;
      if (!provinceData) {
        return `${params.name}<br/>暂无数据`;
      }
      
      // 返回格式化的指标数据
      return `
        <strong>${params.name}</strong><br/>
        总体利用率: ${provinceData.value}%<br/>
        CPU使用率: ${provinceData.cpuUsage}%<br/>
        内存使用: ${provinceData.memoryUsage}GB<br/>
        网络流量: ${provinceData.networkTraffic}MB/s<br/>
        存储: ${provinceData.storage}TB<br/>
        处理能力: ${provinceData.processingPower}<br/>
        计算节点: ${provinceData.computeNodes}
      `;
    } else {
      // 针对城市散点
      return `${params.name}<br/>资源利用率: ${params.value[2]}%`;
    }
  }, []);

  // 处理点击事件
  const handleChartClick = useCallback((params: any) => {
    // 只处理地图系列的点击
    if (params.seriesType === 'map' && params.data && typeof params.data === 'object') {
      const provinceName = params.name as string;
      const provinceData = params.data.data as ProvinceData | null;
      
      // 调用父组件传入的回调函数
      onProvinceSelect(provinceName, provinceData);
    }
  }, [onProvinceSelect]);

  // 初始化地图
  const initMap = useCallback(async () => {
    if (!chartRef.current || !mapDataRef.current || mapInitialized) return;
    
    try {
      const mapData = mapDataRef.current;
      // 加载中国地图GeoJSON数据
      const response = await fetch('/data/china.json');
      if (!response.ok) {
        throw new Error(`HTTP error! Status: ${response.status}`);
      }
      const chinaJson = await response.json();
      
      // 注册地图数据
      echarts.registerMap('china', chinaJson);
      
      // 初始化ECharts实例
      if (!chartInstance.current) {
        chartInstance.current = echarts.init(chartRef.current);
      }
      
      // 从GeoJSON和mapData生成省份数据
      const provinces = chinaJson.features.map((feature: any) => {
        const name = feature.properties.name;
        const provinceData = mapData.provinces[name];
        return {
          name: name,
          value: provinceData ? provinceData.value : 0,
          // 存储其他数据用于tooltip显示
          data: provinceData || null
        };
      });

      // 从mapData构建城市标记数据
      const cityData = mapData.cities.map(city => ({
        name: city.name,
        value: [...city.coordinates, city.value]
      }));

      // 设置地图配置项
      const option = {
        animation: false,
        title: {
          text: mapData.title,
          subtext: mapData.subtitle,
          left: 'center',
          textStyle: {
            color: '#a0a0c0'
          },
          subtextStyle: {
            color: '#7e7e9a'
          }
        },
        tooltip: {
          trigger: 'item',
          formatter: formatTooltip
        },
        visualMap: {
          min: mapData.visualMap.min,
          max: mapData.visualMap.max,
          left: 'left',
          top: 'bottom',
          text: mapData.visualMap.text,
          inRange: {
            color: mapData.visualMap.inRange.color
          },
          calculable: true,
          textStyle: {
            color: '#fff'
          }
        },
        series: [
          {
            name: '资源利用率',
            type: 'map',
            map: 'china',
            roam: mapData.settings.roam,
            zoom: mapData.settings.zoom,
            selectedMode: 'single',
            animation: false,
            label: {
              show: true,
              fontSize: 10,
              color: 'rgba(255, 255, 255, 0.7)'
            },
            itemStyle: {
              areaColor: mapData.settings.areaColor,
              borderColor: mapData.settings.borderColor,
              borderWidth: 1
            },
            emphasis: {
              label: {
                show: true,
                color: '#fff',
                fontSize: 12,
                fontWeight: 'bold'
              },
              itemStyle: {
                areaColor: mapData.settings.highlightColor
              }
            },
            data: provinces
          },
          {
            name: '标记点',
            type: 'scatter',
            coordinateSystem: 'geo',
            symbolSize: 8,
            data: cityData,
            hoverAnimation: false,
            animation: false,
            itemStyle: {
              color: mapData.settings.pointColor,
              shadowBlur: 10,
              shadowColor: '#333'
            },
            zlevel: 1
          }
        ]
      };

      // 使用配置项设置实例
      chartInstance.current.setOption(option);
      
      // 添加点击事件监听
      chartInstance.current.on('click', handleChartClick);
      
      // 标记地图已初始化
      setMapInitialized(true);
    } catch (error) {
      console.error('初始化地图失败:', error);
      setError('初始化地图失败，请刷新页面重试');
    }
  }, [formatTooltip, handleChartClick, mapInitialized]);

  // 当数据加载完成后初始化地图
  useEffect(() => {
    if (!loading && !error && mapDataRef.current && !mapInitialized) {
      initMap();
    }
  }, [loading, error, initMap, mapInitialized]);

  // 响应窗口大小变化
  useEffect(() => {
    const handleResize = () => {
      chartInstance.current?.resize();
    };
    
    window.addEventListener('resize', handleResize);
    
    return () => {
      window.removeEventListener('resize', handleResize);
      if (chartInstance.current) {
        chartInstance.current.off('click');
        chartInstance.current.dispose();
        chartInstance.current = null;
      }
    };
  }, []);

  if (loading) {
    return (
      <div className="map-chart loading-container">
        <div className="loading">加载中...</div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="map-chart error-container">
        <div className="error">{error}</div>
      </div>
    );
  }

  return (
    <div className="map-chart">
      <div ref={chartRef} style={{ height: '100%', width: '100%' }}></div>
    </div>
  );
}); 